package kuba.daos;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;

import kuba.bean.Author;
import kuba.common.BeanLogger;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;

public class AuthorXmlDAO implements AuthorDAO{

    private static int counter =1;
    private String fileName ="authors.xml";
    private List<Author> authors = new ArrayList<Author>();

    public AuthorXmlDAO() {
        deserialize();
        int max=0;
        for (Author author:authors) {
            if (author.getId() >=max) {
                max = author.getId();
            }
        }
        counter = max;
    }
    @SuppressWarnings("unchecked")
    private void deserialize(){

        try{
            FileReader fileReader = new FileReader(fileName);
            authors.clear();
            XStream xstream = new XStream(new StaxDriver());
            xstream.alias("Author", Author.class);
            authors = (ArrayList<Author>)xstream.fromXML(fileReader);    
        }catch(Exception e){
            BeanLogger.getLOGGER().log(Level.WARNING,e.toString());
            serialize();

        }
    }

    private void serialize ( ) {
        XStream xstream = new XStream(new StaxDriver());
        FileWriter fileWriter;

        try {
            fileWriter = new FileWriter(fileName);
            xstream.alias("Author", Author.class);
            xstream.toXML(authors, fileWriter);

        } catch (IOException e) {
            BeanLogger.getLOGGER().log(Level.WARNING,e.toString());
        }

    }

    public Author getById(int id) {
        deserialize();
        for ( Author author:authors) {
            if (author.getId() == id ) {
                return author;
            }
        }
        return null;
    }

    @Override
    public Collection<Author> getAll() {
        deserialize();
        return authors;
    }

    @Override
    public void insert(Author author) {
        deserialize();
        author.setId(++counter);
        authors.add(author);
        serialize();
    }

    @Override
    public void delete(Author author) {
        deserialize();
        authors.remove(author);
        serialize();
    }

    @Override
    public void update(Author author) {
        Author a1 = getById(author.getId());
        if (a1 != null) {
            authors.remove(a1);
            authors.add(author);
            serialize();
        }

    }

}
